﻿using System;
using System.Collections.Specialized;
using System.Diagnostics;

namespace Utilities
{
    public static class ReflectiveModelBinder
    {
        static public TraceSource Logger { get; set; }

        /// <summary>
        /// Binds the model to a name value collection
        /// </summary>
        /// <param name="model"></param>
        /// <param name="collection"></param>
        /// <param name="subscriber"></param>
        public static void Bind(object model, NameValueCollection collection, IPropertyChangedSubscriber subscriber = null)
        {
            TypeAccessor ta = model.GetTypeAccessor();

            foreach (string key in ta.PropertyAccessors.Keys)
            {
                try
                {
                    PropertyAccessor pa = ta.PropertyAccessors[key];
                    string value = collection[key];
                    object oldValue = pa.GetValue(model);

                    object newValue = pa.PropertyType.FromString(value);

                    if (oldValue == newValue)
                    {
                        continue;
                    }

                    if (pa.CanSet)
                    {
                        if (subscriber != null)
                        {
                            pa.SetValueAndNotifyChange(model, newValue, subscriber);
                        }
                        else
                        {
                            pa.SetValue(model, newValue);
                        }
                    }
                }
                catch (Exception exception)
                {
                    if (Logger != null)
                    {
                        Logger.LogError(exception);
                    }
                }
            }
        }
    }
}
